<?php
/** 
*
* @author Tom Martin (Poppertom69) tom.martin60@btinternet.com
* @package Post Bot Mod
* @version $Id$
* @copyright (c) 2008 Poppertom69
* @license http://opensource.org/licenses/gpl-license.php GNU Public License 
*
* @author sTraTo
* @package Autoreply Bot extension for Post Bot Mod (modified by poppertom to work with new version of post bot) 
* @version $Id$
* @copyright (c) 2008 sTraTo
* @license http://opensource.org/licenses/gpl-license.php GNU Public License 
*
*/
if (!defined('IN_PHPBB'))
{
	exit;
}
/*

/**
*
Below you will find some useful tips on how to add extensions to this mods - mod authors please use these functions because it keeps the file tidy and easy to read
If you would like your extension added to the offical post bot please email tom.martin60@btinternet.com with the files and a description of the extension

**ADDING EXTENSIONS**
STEP 1 - Add the required functions to the end of this file before } ?>. (please use a useful name like post_bot_welcome_user)
STEP 2 -  
STEP 3 -
STEP 4 -

**TO GET DATA OUT OF THE POST BOT TABLE**
Much like phpbb the post bot has inbuilt variables to make getting data from the post bot easy
Just use $post_bot['post_bot_config'] so e.g. $post_bot['birthday_subject']
But when including this in a function make sure you add $post_bot to the global list

**TO UPDATE THE POST BOT TABLE**
Much like phpbb the post bot has inbuilt variables to make inserting data into the post bot easy
Just use pb::set_post_bot($post_bot_config, $post_bot_value); so e.g. pb::set_post_bot('auto_post', '1'); or if called in this file use pb::set_post_bot($post_bot_config, $post_bot_value);
And this will update the post bot or insert a new field

**TO ADD TO THE INSTALL EXTENSION LIST**
Locate the available_extensions functions in this file
Find 
	array('post_bot_anonymous_poster'),	
Add after 
	array('post_bot_YOUR EXTENSION'),
Make sure you leave post_bot_ as it makes the config table neater
This will then add your extension to the acp post bot extension list

**TO CHECK IF AN EXTENSION IS INSTALLED**
As the user my not have this extension installed you need to check if it is to proceed
To do so use the following code:
	if (pb::check_extension_status($extension))
	{
		//add you extension code here because it is installed if they are here
	}
	SO e.g
	if (pb::check_extension_status('post_bot_welcome_user'))
	{
		echo"Post Bot welcome user is installed";
	}		
**/

class pb
{
	//Set post bot values - borrowed from phpbb's set config but altered for our needs
	function set_post_bot($post_bot_config, $post_bot_value)
	{
		global $db, $post_bot, $cache;

		$sql = 'UPDATE ' . POST_BOT_TABLE . "
			SET post_bot_value = '" . $db->sql_escape($post_bot_value) . "'
			WHERE post_bot_config = '" . $db->sql_escape($post_bot_config) . "'";
		$db->sql_query($sql);

		if (!$db->sql_affectedrows() && !isset($post_bot[$post_bot_config]))
		{
			$sql = 'INSERT INTO ' . POST_BOT_TABLE . ' ' . $db->sql_build_array('INSERT', array(
				'post_bot_config'	=> $post_bot_config,
				'post_bot_value'	=> $post_bot_value
			));
			$db->sql_query($sql);
		}
		
		$post_bot[$post_bot_config] = $post_bot_value;
		
		$cache->destroy('_post_bot_config');
	}
	
	//Delete value from post bot table
	function delete_value($id)
	{
		global $db, $cache;
		
		$sql = 'DELETE FROM ' . POST_BOT_TABLE . "
			WHERE post_bot_config = '" . $db->sql_escape($id) . "'";
		$db->sql_query($sql);
		
		$cache->destroy('_post_bot_config');
	}

	//Available extensions list
	function available_extensions()
	{
		//4 default welcome user, users birthday, auto reply, anonymous poster
		$extensions = array(
			array('post_bot_welcome_user'),
			array('post_bot_users_birthday'),
			array('post_bot_auto_reply'),
			array('post_bot_anonymous_poster'),	
		);
		
		return $extensions;
	}

	//Check if given extension is installed
	function check_extension_status($extension)
	{
		global $config;	
			
		$extension_status = (isset($config[$extension]) && $config[$extension] == 1) ? true : false;
		
		return $extension_status;
	}

	//used when installing the post bot and in acp when enabling and used in UMIL
	function install_post_bot_extension($extension)
	{
		global $user;
		switch ($extension)
		{
			case 'post_bot_welcome_user':
				pb::set_post_bot('welcome_forum', '2');
				pb::set_post_bot('welcome_subject_1', 'Welcome {USERNAME}!');	
				pb::set_post_bot('welcome_message_1', 'Hello, [b]{USERNAME}[/b]!
					Welcome to {SITE_NAME}. I hope you enjoy your stay, Here is a little information about our site......
					Regards, the team at {SITE_NAME} - {SITE_DESC}!');
				pb::set_post_bot('welcome_bot_id', $user->data['user_id']);
			break;
			
			case 'post_bot_users_birthday':
				pb::set_post_bot('birthday_forum', '2');
				pb::set_post_bot('birthday_subject_1', 'Happy Birthday {USERNAME}!');	
				pb::set_post_bot('birthday_message_1', 'Happy Birthday [b]{USERNAME}[/b] 
					Just to inform you they are {AGE} today and I would like you to join me in saying a big Happy Birthday!');
				pb::set_post_bot('birthday_bot_id', $user->data['user_id']);
			break;
			
			case 'post_bot_auto_reply':
				pb::set_post_bot('auto_reply_forums', '');
				pb::set_post_bot('auto_reply_bot_id', $user->data['user_id']);	
				pb::set_post_bot('auto_reply_time_forums', '');	
				pb::set_post_bot('auto_reply_checks', '1');
				pb::set_post_bot('auto_reply_after', '1');
			break;
			
			case 'post_bot_anonymous_poster':
				pb::set_post_bot('post_bot_id', $user->data['user_id']);
				pb::set_post_bot('post_bot_anon_forums', '');
			break;
		}
	}
	
	function change_auth($user_id, $mode = 'replace', $data = false)
	{
		global $user, $auth, $db;
		
		switch($mode)
		{
			case 'replace':
				$data = array(
					'user_backup' => $user,
					'auth_backup' => $auth,
				);

				$sql = 'SELECT *
					FROM ' . USERS_TABLE . "
					WHERE user_id = '" . $db->sql_escape($user_id) . "'";
				$result	= $db->sql_query($sql);
				$row = $db->sql_fetchrow($result);
				$row['is_registered'] = true;
				
				$db->sql_freeresult($result);
				
				$user->data = array_merge($user->data, $row);
				$auth->acl($user->data);
				
				unset($row);
				
				return $data;
			break;
			
			case 'restore':				
				$user = $data['user_backup'];
				$auth = $data['auth_backup'];
				unset($data);
			break;
		}
	}
	
	function get_vars($mode, $data)
	{
		global $config, $phpbb_root_path;
	
		//Set standard vars
		$vars = array(
			'{USERNAME}'		=> $data['username'],
			'{USER_ID}'			=> $data['user_id'],
			'{SITE_NAME}'		=> $config['sitename'],
			'{SITE_DESC}'		=> $config['site_desc'],
			'{BOARD_SIG}'		=> $config['board_email_sig'],
			'{BOARD_EMAIL}'		=> $config['board_email'],
			'{ROOT_PATH}'		=> $phpbb_root_path,
			'{BOARD_LOC}'		=> $config['server_protocol'] . $config['server_name'] . $config['script_path'],
			'{BOARD_ROOT}'		=> $config['server_protocol'] . $config['server_name'],
		);
		
		switch ($mode)
		{
			case 'welcome':
			
			break;
			
			case 'birthday':
				$vars = array_merge($vars, array(
					'{AGE}'	=>	$data['age'],
				));
			break;
			
			case 'auto_reply':
				$vars = array_merge($vars, array(
					'{SUBJECT}'	=>	$data['subject'],
				));
			break;
		}
		
		return $vars;
	}

	//Real extension functions start here

	//Welcome user
	function post_bot_welcome_user()
	{
		global $post_bot, $user, $phpbb_root_path, $phpEx;

		if (!function_exists('submit_post'))
		{
			include($phpbb_root_path . 'includes/functions_posting.' . $phpEx);
		}
		
		$user_id 	= $user->data['user_id'];
		$username 	= $user->data['username'];	
		
		//Get post bots permissions
		$perms = pb::change_auth($post_bot['welcome_bot_id']);

		//Parse the text with the bbcode parser and write into $text
		$subject	= utf8_normalize_nfc($post_bot['welcome_subject_1']);
		$message	= utf8_normalize_nfc($post_bot['welcome_message_1']);
		
		//Set data for vars
		$data = array(
			'username'	=> $username,
			'user_id'	=> $user_id,
		);
		
		//Correctly assign variables.
		$welcome_vars = pb::get_vars('welcome', $data);

		$message = str_replace(array_keys($welcome_vars), array_values($welcome_vars), $message);
		$subject = str_replace(array_keys($welcome_vars), array_values($welcome_vars), $subject);
		
		// variables to hold the parameters for submit_post
		$poll = $uid = $bitfield = $options = ''; 
		generate_text_for_storage($subject, $uid, $bitfield, $options, false, false, false);
		generate_text_for_storage($message, $uid, $bitfield, $options, true, true, true);

		$data = array( 
			'forum_id'			=> $post_bot['welcome_forum'],
			'icon_id'			=> false,

			'enable_bbcode'		=> true,
			'enable_smilies'	=> true,
			'enable_urls'		=> true,
			'enable_sig'		=> true,

			'message'			=> $message,
			'post_checksum'		=> '',
			'message_md5'		=> '',
					
			'bbcode_bitfield'	=> $bitfield,
			'bbcode_uid'		=> $uid,

			'post_edit_locked'	=> 0,
			'topic_title'		=> $subject,
			'notify_set'		=> false,
			'notify'			=> false,
			'post_time' 		=> 0,
			'forum_name'		=> '',
			'enable_indexing'	=> true,
			
			'topic_approved'	=> true,
			'post_approved'		=> true,
		);

		submit_post('post', $subject, '', POST_NORMAL, $poll, $data);	
		
		//Restore user permissions
		pb::change_auth('', 'restore', $perms);	
	}	
	
	//Birthday message	
	function post_bot_user_birthday($username, $user_id, $age)
	{
		global $user, $db, $phpbb_root_path, $phpEx, $post_bot;

		if (!function_exists('submit_post'))
		{
			include($phpbb_root_path . 'includes/functions_posting.' . $phpEx);
		}
		
		// Parse the text with the bbcode parser and write into $text
		$subject		= utf8_normalize_nfc($post_bot['birthday_subject_1']);
		$message		= utf8_normalize_nfc($post_bot['birthday_message_1']);
		$birthday_forum = $post_bot['birthday_forum'];
		
		//Set data for vars
		$data = array(
			'username'	=> $username,
			'user_id'	=> $user_id,
			'age'		=> $age,
		);
		
		//Correctly assign variables.
		$birthday_vars = pb::get_vars('birthday', $data);
		
		$subject = str_replace(array_keys($birthday_vars), array_values($birthday_vars), $subject);
		$message = str_replace(array_keys($birthday_vars), array_values($birthday_vars), $message);
		
		$sql = 'SELECT post_time
			FROM ' . POSTS_TABLE . "
			WHERE post_subject = '" . $db->sql_escape($subject) . "'";
		$result = $db->sql_query($sql);	
		$row = $db->sql_fetchrow($result);
		$db->sql_freeresult($result);
		
		if ($db->sql_affectedrows())
		{
			$cur_time 		= time();
			//Add 360 days to post time means we we can start a new topic if year on
			$future_time 	= $row['post_time'] + 31104000;
			
			$proceed = ($future_time <= $cur_time) ? true : false;
		}
		else
		{
			$proceed = true;
		}		
			
		if($proceed)
		{ 	
			//Get post bots permissions
			$perms = pb::change_auth($post_bot['birthday_bot_id']);
			
			// variables to hold the parameters for submit_post
			$poll = $uid = $bitfield = $options = ''; 
			generate_text_for_storage($subject, $uid, $bitfield, $options, false, false, false);
			generate_text_for_storage($message, $uid, $bitfield, $options, true, true, true);

			$data = array( 
				'forum_id'			=> $birthday_forum,
				'icon_id'			=> false,

				'enable_bbcode'		=> true,
				'enable_smilies'	=> true,
				'enable_urls'		=> true,
				'enable_sig'		=> true,

				'message'			=> $message,
				'post_checksum'		=> '',
				'message_md5'		=> '',
					
				'bbcode_bitfield'	=> $bitfield,
				'bbcode_uid'		=> $uid,

				'post_edit_locked'	=> 0,
				'topic_title'		=> $subject,
				'notify_set'		=> false,
				'notify'			=> false,
				'post_time' 		=> 0,
				'forum_name'		=> '',
				'enable_indexing'	=> true,
			
				'topic_approved'	=> true,
				'post_approved'		=> true,
			);

			submit_post('post', $subject, '', POST_NORMAL, $poll, $data);

			//Restore user permissions
			pb::change_auth('', 'restore', $perms);	
		}
	}

	//Auto Reply - check if in forum
	function check_autoreply($forum_id, $subject, $topic_id)
	{
		global $post_bot, $user;
		
		$forums = explode(", ", $post_bot['auto_reply_forums']);
		
		if (in_array($forum_id, $forums))
		{
			$data = array(
				'username'	=> $user->data['username'],
				'user_id'	=> $user->data['user_id'],
			);
		
			pb::autoreply_post($subject, $forum_id, $topic_id, $data);
			
			unset($data);
		}	
	}
	
	//Auto Reply - Check to see if we need to post a timed delay message - useful for support forums to inform user that they will get help
	function check_timed_auto_reply()
	{
		global $post_bot, $config, $db;
		
		$check_in_mins = $post_bot['auto_reply_checks'] * 60;
		$need_to_check = ($config['post_bot_auto_lc'] + $check_in_mins <= time()) ? true : false;
		
		if ($need_to_check)
		{	
			$forums = explode(", ", $post_bot['auto_reply_time_forums']);
			$reply_after = $post_bot['auto_reply_after'] * 60;
			
			foreach ($forums as $key => $forum_id)
			{		
				$sql = 'SELECT topic_id, forum_id, topic_title, topic_poster, topic_first_poster_name
					FROM ' . TOPICS_TABLE . ' 
					WHERE topic_replies = 0
						AND topic_approved = 1
						AND forum_id = ' . $forum_id . '
						AND topic_time <= topic_time + ' . $reply_after;
				$result = $db->sql_query($sql);
				
				while ($row = $db->sql_fetchrow($result))
				{
					$data = array(
						'user_id'	=> $row['topic_poster'],
						'username'	=> $row['topic_first_poster_name'],
					);
				
					pb::autoreply_post($row['topic_title'], $row['forum_id'], $row['topic_id'], $data, true);
					
					unset($data);
				}
				
				$db->sql_freeresult($result);
			}
			
			set_config('post_bot_auto_lc', time());
		}
	}

	//Auto Reply - post message 
	function autoreply_post($subject, $forum_id, $topic_id, $data, $timed = false)
	{
		global $user, $phpbb_root_path, $phpEx, $post_bot;

		if (!function_exists('submit_post'))
		{
			include($phpbb_root_path . 'includes/functions_posting.' . $phpEx);
		}
		
		$user_id 	= $data['user_id'];
		$username 	= $data['username'];
		
		unset($data);
		
		//Get post bots permissions
		$perms = pb::change_auth($post_bot['auto_reply_bot_id']);
		
		if ($timed)
		{
			$text = $post_bot['auto_reply_timed_message_' . $forum_id];
		}
		else
		{
			$text = $post_bot['auto_reply_message_' . $forum_id];
		}
		
		$subject	= utf8_normalize_nfc($subject);
		$message	= utf8_normalize_nfc($text);
		
		//Set data for vars
		$data = array(
			'username'	=> $username,
			'user_id'	=> $user_id,
			'subject'	=> $subject,
		);
		
		//Correctly assign variables.
		$auto_vars = pb::get_vars('auto_reply', $data);
		
		$message = str_replace(array_keys($auto_vars), array_values($auto_vars), $message);
		$subject = str_replace(array_keys($auto_vars), array_values($auto_vars), $subject);
		
		// Variables to hold the parameters for submit_post
		$poll = $uid = $bitfield = $options = ''; 
		
		generate_text_for_storage($subject, $uid, $bitfield, $options, false, false, false);
		generate_text_for_storage($message, $uid, $bitfield, $options, true, true, true);
		
		$data = array( 
			'forum_id'			=> $forum_id,
			'icon_id'			=> false,
			'topic_id'			=> $topic_id,
			
			'enable_bbcode'		=> true,
			'enable_smilies'	=> true,
			'enable_urls'		=> true,
			'enable_sig'		=> true,
			
			'message'			=> $message,
			'post_checksum'		=> '',
			'message_md5'		=> '',
			
			'bbcode_bitfield'	=> $bitfield,
			'bbcode_uid'		=> $uid,
			
			'post_edit_locked'	=> 1,
			'topic_title'		=> $subject,
			'notify_set'		=> false,
			'notify'			=> false,
			'post_time' 		=> 0,
			'forum_name'		=> '',
			'enable_indexing'	=> true,
		);
		
		submit_post('reply', $subject, '', POST_NORMAL, $poll, $data);
		
		//Restore user permissions
		pb::change_auth('', 'restore', $perms);
	}
}
?>
